package com.beiye.drivertransport.SubActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.adapter.ListBaseAdapter;
import com.beiye.drivertransport.adapter.SuperViewHolder;
import com.beiye.drivertransport.bean.UnUserLearnBean;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.Utils;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.githang.statusbar.StatusBarCompat;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

//未完成学习驾驶员
public class UnfinishedLearningActivity extends TwoBaseAty {


    LRecyclerView lv_Unfinish;

    ImageView img_Unfinish_back;

    TextView tv_Unfinishdate;

    View empty_view;
    private int firstIndex = 1;
    private int pageSize = 10;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private UnfinishedLearningApt unfinishedLearningApt;


    @Override
    public int getLayoutId() {
        return R.layout.activity_unfinished_learning;
    }


    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_Unfinish_back) {
            SharedPreferences sp = getSharedPreferences("adIdandorgid2",
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.clear();
            edit.commit();
            finish();
        } else if (id == R.id.tv_Unfinish) {
            showDateYearpopwindow();
        }

    }


    @Override
    public void onBackPressed() {
        SharedPreferences sp = getSharedPreferences("adIdandorgid2",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.clear();
        edit.commit();
        super.onBackPressed();
    }

    private void showDateYearpopwindow() {
        TimePickerView pvTime = new TimePickerBuilder(UnfinishedLearningActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date2, View v) {//选中事件回调
                String time = getTime(date2);
                tv_Unfinishdate.setText(time);
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM");// HH:mm:ss

                String format1 = simpleDateFormat1.format(date2);
                SharedPreferences sp = getSharedPreferences("adIdandorgid2",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("format1",format1);
                edit.commit();
                lv_Unfinish.refresh();
                requestData();
//                Calendar cal = Calendar.getInstance();
//                cal.set(Calendar.YEAR, Integer.parseInt(year.substring(0, 4)));
//                cal.set(Calendar.MONTH, Integer.parseInt(month.substring(0, 2)));
//                cal.set(Calendar.DAY_OF_MONTH, 1);
//                cal.add(Calendar.DAY_OF_MONTH, -1);
//                Date lastDate = cal.getTime();
//                cal.set(Calendar.DAY_OF_MONTH, 1);
//                Date firstDate = cal.getTime();
//                String endTime = new SimpleDateFormat("yyyy-MM-dd 23:59:59").format(lastDate);
//                String beginTime = new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(firstDate);
            }
        })
                .setType(new boolean[]{true, true, false, false, false, false})//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setTitleSize(20)//标题文字大小
//                        .setTitleText("请选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLACK)//确定按钮文字颜色
                .setCancelColor(Color.BLACK)//取消按钮文字颜色
//                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();


    }
    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");
        return format.format(date);
    }

    @Override
    public void initData() {
        lv_Unfinish = (LRecyclerView) findViewById(R.id.lv_Unfinish);
        img_Unfinish_back = (ImageView) findViewById(R.id.img_Unfinish_back);
        tv_Unfinishdate = (TextView) findViewById(R.id.tv_Unfinish);
        empty_view = (View) findViewById(R.id.empty_view);

        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        initUi();
        Bundle bundle = getIntent().getExtras();
       // String adId = bundle.getString("adId");
        String orgId = bundle.getString("orgId");
        int minPer = bundle.getInt("minPer");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        String format = simpleDateFormat.format(date);
        tv_Unfinishdate.setText(format);
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM");// HH:mm:ss
        String format1 = simpleDateFormat1.format(date);
        SharedPreferences sp = getSharedPreferences("adIdandorgid2",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
      //  edit.putString("adId",adId);
        edit.putString("orgId",orgId);
        edit.putString("format1",format1);
        edit.putInt("minPer",minPer);
        edit.commit();
    }

    private void initUi() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(UnfinishedLearningActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        lv_Unfinish.setLayoutManager(layoutManager);
        unfinishedLearningApt = new UnfinishedLearningApt(UnfinishedLearningActivity.this);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(unfinishedLearningApt);
        lv_Unfinish.setAdapter(lRecyclerViewAdapter);
        lv_Unfinish.setFooterViewColor(R.color.colorAccent, R.color.dark, android.R.color.white);
        lv_Unfinish.setFooterViewHint("拼命加载中", "已经全部为你呈现了", "网络不给力啊，点击再试一次吧");
        lv_Unfinish.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                firstIndex = 1;
                requestData();
            }
        });

        lv_Unfinish.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore() {

                firstIndex += pageSize;
                requestData();
            }
        });
        empty_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lv_Unfinish.refresh();
            }
        });

        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (Utils.isFastDoubleClick()) {
                    return ;
                }
                String userId = unfinishedLearningApt.getDataList().get(position).getUserId();
                SharedPreferences sp = getSharedPreferences("adIdandorgid2",
                        Context.MODE_PRIVATE);
                String orgId = sp.getString("orgId", "");
                int minPer = sp.getInt("minPer", 0);
                Bundle bundle = new Bundle();
                bundle.putString("orgId", orgId);
                bundle.putString("userId", userId);
                bundle.putInt("minPer", minPer);
                startActivity(UnfinishLearnRecordActivity.class, bundle);
            }
        });
        lv_Unfinish.refresh();

    }

    @Override
    public void requestData() {
        SharedPreferences sp = getSharedPreferences("adIdandorgid2",
                Context.MODE_PRIVATE);
        String orgId = sp.getString("orgId", "");
        String format1 = sp.getString("format1", "");
        new Login().getfindUnChUserLearning(orgId,format1,format1,firstIndex,pageSize,this, 1);
    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if(what==1) {
            UnUserLearnBean unUserLearnBean = JSON.parseObject(result, UnUserLearnBean.class);
            if (unUserLearnBean != null) {
                try {

                    if (unUserLearnBean.getRows() != null && unUserLearnBean.getRows().size() > 0) {
                        lv_Unfinish.setVisibility(View.VISIBLE);
                        if (firstIndex == 1) {
                            unfinishedLearningApt.clear();
                            unfinishedLearningApt.setDataList(unUserLearnBean.getRows());
                        } else {
                            unfinishedLearningApt.addAll(unUserLearnBean.getRows());
                        }

                        if (unUserLearnBean.getRows().size() < pageSize) {
                            lv_Unfinish.setNoMore(true);
                        }
                    } else {
                        if (firstIndex == 1) {//第一页
                            lv_Unfinish.setEmptyView(empty_view);
                            unfinishedLearningApt.clear();
                        } else {
                            lv_Unfinish.setNoMore(true);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                lv_Unfinish.refreshComplete(unUserLearnBean.getRows() == null ? 0 : unUserLearnBean.getRows().size());
                lRecyclerViewAdapter.notifyDataSetChanged();
            }
        }
        super.onSuccess(result, call, response, what);
    }
    public class UnfinishedLearningApt extends ListBaseAdapter<UnUserLearnBean.RowsBean> {

        protected Context context = null;


        public UnfinishedLearningApt(Context context) {
            super(context);
            this.context = context;
        }

        @Override
        public int getLayoutId() {
            return R.layout.unfinishedlearn_item_layout;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            TextView tv_name = holder.getView(R.id.tv_Unfinish1);
            TextView tv_phone = holder.getView(R.id.tv_Unfinish3);
            String userName = getDataList().get(position).getUserName();
            String userMobile = getDataList().get(position).getUserMobile();
            if (userName == null) {
                tv_name.setText("");
            } else {
                tv_name.setText(userName);
            }
            if (userMobile == null) {
                tv_phone.setText("");
            } else {
                tv_phone.setText(userMobile);
            }

        }


    }

}
